package com.yitiao.base.collection;

import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

public class TreeMapExample {

    public static void main(String[] args) {
        // 自定义比较器，按照键的长度进行排序
        Comparator<String> customComparator = Comparator.comparingInt(String::length);

        // 使用自定义比较器创建TreeMap
//        TreeMap<String, Integer> treeMap = new TreeMap<>(customComparator);
        // 使用自定义比较器创建TreeMap
        TreeMap<String, Integer> treeMap = new TreeMap<>();

        // 向TreeMap中添加元素
        treeMap.put("apple", 1);
        treeMap.put("banana", 2);
        treeMap.put("orange", 3);

        // 遍历输出TreeMap
        for (String key : treeMap.keySet()) {
            System.out.println(key + ": " + treeMap.get(key));
        }

        // 创建一个线程安全的TreeMap
        Map<String, Integer> synchronizedTreeMap = Collections.synchronizedSortedMap(new TreeMap<>());

        // 向线程安全的TreeMap中添加元素
        synchronizedTreeMap.put("apple", 1);
        synchronizedTreeMap.put("banana", 2);
        synchronizedTreeMap.put("orange", 3);

        // 遍历输出线程安全的TreeMap
        synchronized (synchronizedTreeMap) {
            for (String key : synchronizedTreeMap.keySet()) {
                System.out.println(key + ": " + synchronizedTreeMap.get(key));
            }
        }
    }

}
